package com.zzyl.nursing.service.impl;

import java.io.*;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;

import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson2.JSON;
import com.zzyl.common.ai.AiModuleInvoker;
import com.zzyl.common.constant.CacheConstants;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.common.utils.IDCardUtils;
import com.zzyl.common.utils.StringUtils;
import com.zzyl.nursing.vo.HealthReportVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.HealthAssessmentMapper;
import com.zzyl.nursing.domain.HealthAssessment;
import com.zzyl.nursing.service.IHealthAssessmentService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

/**
 * 健康评估Service业务层处理
 * 
 * @author wangjiaxin
 * @date 2025-01-06
 */
@Service
public class HealthAssessmentServiceImpl extends ServiceImpl<HealthAssessmentMapper, HealthAssessment> implements IHealthAssessmentService
{
    @Autowired
    private HealthAssessmentMapper healthAssessmentMapper;
    @Autowired
    private RedisTemplate<String,String> redisTemplate;
    @Autowired
    private AiModuleInvoker aiModuleInvoker;

    /**
     * 查询健康评估
     * 
     * @param id 健康评估主键
     * @return 健康评估
     */
    @Override
    public HealthAssessment selectHealthAssessmentById(Long id)
    {
        return healthAssessmentMapper.selectById(id);
    }

    /**
     * 查询健康评估列表
     * 
     * @param healthAssessment 健康评估
     * @return 健康评估
     */
    @Override
    public List<HealthAssessment> selectHealthAssessmentList(HealthAssessment healthAssessment)
    {
        return healthAssessmentMapper.selectHealthAssessmentList(healthAssessment);
    }

    /**
     * 新增健康评估
     * 
     * @param healthAssessment 健康评估
     * @return 结果
     */
    @Override
    public Long insertHealthAssessment(HealthAssessment healthAssessment)
    {
        //1先根据身份证从redis中查询体检内容
        String o = (String) redisTemplate.opsForHash().get(CacheConstants.HEALTH_REPORT, healthAssessment.getIdCard());
        //2 如果redis中存在，则直接返回
        if(StringUtils.isEmpty(o)){
            throw new  BaseException("请先上传体检报告");
        }
        redisTemplate.opsForHash().delete(CacheConstants.HEALTH_REPORT, healthAssessment.getIdCard());
        //3使用百度千帆大模型进行健康评估
        String content =  healthAssess(o);
        String qianFanResult = aiModuleInvoker.qianfanInvoker(content);

        //4 将结果存入数据库
        Long id =  insertHealthResult(qianFanResult,healthAssessment);
        return id;
    }

    private Long insertHealthResult(String qianFanResult, HealthAssessment healthAssessment) {
        HealthReportVo healthReportVo = JSON.parseObject(qianFanResult, HealthReportVo.class);

        healthAssessment.setBirthDate(IDCardUtils.getBirthDateByIdCard(healthAssessment.getIdCard()));
        healthAssessment.setAge(IDCardUtils.getAgeByIdCard(healthAssessment.getIdCard()));
        healthAssessment.setGender(IDCardUtils.getGenderFromIdCard(healthAssessment.getIdCard()));

        double healthScore= healthReportVo.getHealthAssessment().getHealthIndex();
        healthAssessment.setHealthScore(String.valueOf(healthScore));
        healthAssessment.setRiskLevel(healthReportVo.getHealthAssessment().getRiskLevel());
        healthAssessment.setSuggestionForAdmission(healthScore>=60?0:1);
        healthAssessment.setNursingLevelName(getNursingLevelName(healthScore));
        healthAssessment.setAdmissionStatus(1);
        healthAssessment.setTotalCheckDate(healthReportVo.getTotalCheckDate());

        healthAssessment.setAssessmentTime(LocalDateTime.now());
        healthAssessment.setReportSummary(healthReportVo.getSummarize());

        healthAssessment.setDiseaseRisk(JSON.toJSONString(healthReportVo.getRiskDistribution()));
        healthAssessment.setAbnormalAnalysis(JSON.toJSONString(healthReportVo.getAbnormalData()));
        healthAssessment.setSystemScore(JSON.toJSONString(healthReportVo.getSystemScore()));

        healthAssessmentMapper.insert(healthAssessment);
        return healthAssessment.getId();
    }

    private String getNursingLevelName(double healthScore) {
        if(healthScore>100 || healthScore<0){
            throw new BaseException("健康评分异常");
        }
        if(healthScore>=90){
            return "四级护理等级";
        }else if(healthScore>=80){
            return "三级护理等级";
        }else if(healthScore>=70){
            return "二级护理等级";
        }else if(healthScore>=60){
            return "一级护理等级";
        }else {
            return "特鸡护理等级";
        }
    }

    private String healthAssess(String o) {
        try(
//                InputStream is = new FileInputStream("zzyl-nursing-platform/src/main/resources/mapper/propts/healthAssessment.txt");
//                Reader r = new InputStreamReader(is);
//                BufferedReader br = new BufferedReader(r);
                InputStream is = this.getClass().getClassLoader().getResourceAsStream("mapper\\propts\\healthAssessment.txt");
                InputStreamReader isr = new InputStreamReader(is);
                BufferedReader br = new BufferedReader(isr);
            ) {

            StringBuilder context = new StringBuilder();
            String line;
            while ((line = br.readLine())!= null){
                context.append(line);
                if(line.contains("体检内容如下：")){
                    context.append(o);
                }
            }
            return context.toString();
        } catch (IOException e) {
            throw new BaseException("读取体检报告是出现了异常");
        }
    }

    /**
     * 修改健康评估
     * 
     * @param healthAssessment 健康评估
     * @return 结果
     */
    @Override
    public int updateHealthAssessment(HealthAssessment healthAssessment)
    {
        return healthAssessmentMapper.updateById(healthAssessment);
    }

    /**
     * 批量删除健康评估
     * 
     * @param ids 需要删除的健康评估主键
     * @return 结果
     */
    @Override
    public int deleteHealthAssessmentByIds(Long[] ids)
    {
        return healthAssessmentMapper.deleteBatchIds(Arrays.asList(ids));
    }

    /**
     * 删除健康评估信息
     * 
     * @param id 健康评估主键
     * @return 结果
     */
    @Override
    public int deleteHealthAssessmentById(Long id)
    {
        return healthAssessmentMapper.deleteById(id);
    }
}
